//
//  UIScrollerView+JJRefresh.swift
//  JJToolSwift
//
//  Created by heihei on 2024/5/16.
//

import Foundation
import MJRefresh

public extension UIScrollView {
    
    /// 添加下拉刷新
    /// - Parameter complete: 刷新回调
    func addRefreshHeader(complete: @escaping() -> Void) {
        switch JJHUDConfig.animateType {
        case .lottie:
            let header = LottieRefreshHeader()
            header.refreshingBlock = {
                DispatchQueue.main.async {
                    complete()
                }
            }
            mj_header = header
        case .gif:
            let header = GifRefreshHeader()
            header.refreshingBlock = {
                DispatchQueue.main.async {
                    complete()
                }
            }
            mj_header = header
        default:
            let header = MJRefreshNormalHeader()
            header.setTitle("下拉刷新", for: .idle)
            header.setTitle("释放更新", for: .pulling)
            header.setTitle("正在刷新", for: .refreshing)
            header.lastUpdatedTimeLabel?.isHidden = true
            header.refreshingBlock = {
                DispatchQueue.main.async {
                    complete()
                }
            }
            mj_header = header
        }
    }
    
    /// 添加自定义下拉refresh
    /// - Parameters:
    ///   - header: 刷新动画header
    ///   - complete: 刷新回调
    func addCustomerRefreshHeader(header: MJRefreshHeader, complete: @escaping() -> Void) {
        header.refreshingBlock = {
            DispatchQueue.main.async {
                complete()
            }
        }
        mj_header = header
    }
    
    /// 结束下拉刷新
    func endHeaderRefresh() {
        DispatchQueue.main.async { [weak self] in
            guard let `self` = self else { return }
            mj_footer?.resetNoMoreData()
            mj_header?.endRefreshing()
        }
    }
    
    /// 添加下拉加载
    /// - Parameter complete: 加载回调
    func addRefreshFooter(complete: @escaping() -> Void) {
        let footer = MJRefreshAutoNormalFooter()
        footer.setTitle("上拉加载更多", for: .idle)
        footer.setTitle("正在加载", for: .refreshing)
        footer.setTitle("没有更多数据", for: .noMoreData)
        footer.isHidden = true
        footer.refreshingBlock = {
            DispatchQueue.main.async {
                complete()
            }
        }
        mj_footer = footer
    }
    
    /// 结束下拉刷新
    func endFooterRefresh(hasMore: Bool) {
        DispatchQueue.main.async { [weak self] in
            guard let `self` = self else { return }
            hasMore ? mj_footer?.endRefreshing() : mj_footer?.endRefreshingWithNoMoreData()
        }
    }
}
